package com.molichuxing.gateway.api.services.impl;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.molichuxing.framework.exception.BizException;
import com.molichuxing.framework.result.ResponseResult;
import com.molichuxing.gateway.api.services.WechatApiService;
import com.molichuxing.gateway.bff.user.entity.response.UserVo;
import com.molichuxing.gateway.bff.user.entity.response.WechatConfigVo;
import com.molichuxing.gateway.bff.user.entity.response.WechatUserVo;
import com.molichuxing.gateway.bff.user.services.UserBffService;
import com.molichuxing.gateway.utils.redis.TokenUtil;

import io.swagger.annotations.Api;
import me.chanjar.weixin.common.exception.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpConfigStorage;
import me.chanjar.weixin.mp.api.WxMpInMemoryConfigStorage;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl;
import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken;
import springfox.documentation.annotations.ApiIgnore;

/**
 * 微信相关接口
 * 
 * @author 李义广
 * @date 2019-10-29
 *
 */
@Api(tags = "微信相关接口")
@RestController
@RequestMapping("/wechat")
public class WechatApiServiceImpl extends RootApiService implements WechatApiService {
	private Logger logger = LoggerFactory.getLogger(this.getClass());

	@Value("${wechat.appid}")
	private String appid;

	@Value("${wechat.appsecret}")
	private String appsecret;
	
	@Resource
	private UserBffService userBffService;
	
	@Resource
	private TokenUtil tokenUtil;

	/**
	 * 根据code信息获取openid
	 *
	 * @param code
	 * @param state
	 * @return
	 */
	@Override
	@GetMapping(value = "/openid")
	public ResponseResult<WechatUserVo> getOpenId(@RequestParam String code) {
		logger.info("【微信授权】code="+code );
		ResponseResult<WechatUserVo> result=new ResponseResult<WechatUserVo>();
		try {
			// 获取openid
			WxMpService wxMpService = new WxMpServiceImpl();
			WxMpConfigStorage wxMpConfigStorage = new WxMpInMemoryConfigStorage();
			((WxMpInMemoryConfigStorage) wxMpConfigStorage).setAppId(appid);
			((WxMpInMemoryConfigStorage) wxMpConfigStorage).setSecret(appsecret);
			wxMpService.setWxMpConfigStorage(wxMpConfigStorage);
			WxMpOAuth2AccessToken wxMpOAuth2AccessToken = wxMpService.oauth2getAccessToken(code);
			logger.info("【微信授权】" + wxMpOAuth2AccessToken);
			String openId = wxMpOAuth2AccessToken.getOpenId();
			// 通过openid获取用户信息
			UserVo userVo = userBffService.getUserByOpenId(openId);
			WechatUserVo wechatUserVo = new WechatUserVo();
			wechatUserVo.setOpenId(openId);
			// 判断用户是否存在
			if (userVo == null) {
				return result.success(wechatUserVo);
			}
			// 该用户存在，直接登录
			String token = tokenUtil.setWechatUserToken(userVo, openId);
			wechatUserVo.setToken(token);
			return result.success(wechatUserVo);
		} catch (WxErrorException e) {
			logger.error("【微信授权】获取openid失败：" + e);
			return result.error("【微信授权】获取openid失败");
		} catch (Exception e) {
			logger.error("获取openid接口异常：" + e);
			return result.error("获取openid接口异常");
		}
	}
	
	/**
	 * 获取微信签名
	 * @return
	 */
	@Override
	@GetMapping(value = "/ticket")
	public ResponseResult<WechatConfigVo> getWechatConfig() {
		ResponseResult<WechatConfigVo> result=new ResponseResult<WechatConfigVo>();
		try {
			WechatConfigVo wechatConfig = userBffService.getWechatConfig();
			return result.success(wechatConfig);
		} catch (BizException e) {
			logger.error("获取微信签名接口异常：" + e);
			return result.error(e.getMessage());
		} catch (Exception e) {
			logger.error("获取微信签名接口异常" + e);
			return result.error("获取微信签名接口异常");
		}
	}
}
